#include "device_controller_ui.h"

#include <QDebug>

DeviceControllerUI::DeviceControllerUI() {
    serial = new SerialPortEngine();
    connect(serial, &SerialPortEngine::receiveBytesIndication, this, &DeviceControllerUI::handleSerialPortRxIndication);

//    serial->connectDevice("COM2");
}

void DeviceControllerUI::updateDeviceList() {
    // 调用设备引擎的接口
    serial->scanExistenceDevice();
    // 向View层发送信号
    emit deviceListChanged(serial->nameList());
    qDebug() << "qml signal refresh debug ok";
}

void DeviceControllerUI::updateSettings(int parameter1, int parameter2, int parameter3, int parameter4) {
    // 串口更新设置 波特率、数据位、校验、停止位
    serial->updateSettings(parameter1, parameter2, parameter3, parameter4);
}

void DeviceControllerUI::connectDevice(const QString &name) {
    bool isConnected = false;
    if(serial->connectDevice(name) == SerialPortEngine::SERIAL_SUCCESS) {
        isConnected = true;
    }
    emit deviceStatusChanged(isConnected);
    qDebug() << "qml signal connect debug ok";

}

void DeviceControllerUI::disConnectDevice() {
    serial->disConnectDevice();
    emit deviceStatusChanged(false);
}

void DeviceControllerUI::sendMessage(const QString &message) {
    PduInfoType pdu;
    QByteArray bytes = message.toLatin1();
//    const unsigned char da[] = message.toStdString();
    pdu.SduDataPtr = (unsigned char*)bytes.data();
    pdu.SduLength = bytes.length();
    serial->sendMessage(&pdu);
}

void DeviceControllerUI::handleSerialPortRxIndication(const PduInfoType *pdu) {
    // 数据分包
    QString str((const char*)pdu->SduDataPtr);
    emit deviceRxIndication(str);
    serial->receiveBytesConfirmation();
}
